package factorytest.iflytek.com.einkiflytekfactorytest.playerutils;

import android.content.Context;
import android.os.Handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import factorytest.iflytek.com.einkiflytekfactorytest.codec.BaseCodec;
import factorytest.iflytek.com.einkiflytekfactorytest.codec.PcmCodec;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;

/**
 * 音频播放工具
 *
 * @author 奎华
 */
public class MediaPlayerTool extends PlayEventConstant {

    private static MediaPlayerTool instance;
    private Context mContext;
    private Handler mHandler;
    private BaseCodec mBaseCodec;
    private Thread playThread;

    public static MediaPlayerTool getInstance(Context context, Handler handler) {
        if (null == instance) {
            instance = new MediaPlayerTool(context, handler);
        }
        return instance;
    }

    public MediaPlayerTool(Context context, Handler handler) {
        this.mContext = context;
        this.mHandler = handler;
    }

    /**
     * 播放数据，适用于播放小音频文件
     *
     * @param data
     */
    public void play(byte[] data) {

    }

    /**
     * 播放pcm文件
     *
     * @param filePath
     */
    public void playPcm(String filePath) {
        if (null == filePath) {
            return;
        }
        mBaseCodec = PcmCodec.getInstance();
        //获取文件输入流，文件大小
        File file = new File(filePath);
        if (null == file || !file.exists()) {
            DebugLog.e("MediaPlayerTool, pcm文件不存在");
            return;
        }
        InputStream ins = null;
        int fileSize = 0;
        try {
            ins = new FileInputStream(file);
            fileSize = ins.available();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (ins != null && fileSize > 0) {
            //首先进行 音频解码
            mBaseCodec.decode(ins);
            //每次从输入流中获取指定大小数据
            byte[] data = mBaseCodec.fetchData(fileSize);
            if (data != null) {
                playThread = new Thread(new MyThread(data, mHandler));
                playThread.start();
            }
        }

    }

    /**
     * 播放wav文件
     *
     * @param filePath
     */
    public void playWav(String filePath) {

    }

    public void stop() {
        if (playThread != null) {
            playThread.interrupt();
            playThread = null;
        }
        if (mBaseCodec != null) {
            mBaseCodec.release();
        }
    }


}
